package com.zsj.queue;

import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;


/**
 * @author zsj
 * @date 2023/12/13.
 * 环形链表实现队列
 */
public class LinkedListQueue<E>
        implements Queue<E>,
        Iterable<E> {

    //内部类
    private static class Node<E> {
        Node<E> next;
        E value;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    //头 哨兵节点
    private Node<E> head = new Node<>(null, null);

    //尾
    private Node<E> tail = head;

    //节点数量
    private int size;

    //整个队列容量
    private int capacity = Integer.MAX_VALUE;

    //代码块
    {
        tail.next = head;
    }

    //可以给队列一个属性为
    public LinkedListQueue() {
    }

    public LinkedListQueue(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public boolean offer(E value) {
        //队列容量已满时不允许添加
        if (isFull()) return false;
        //构建新元素
        Node<E> eNode = new Node<>(value, head);
        tail.next = eNode;
        tail = eNode;
        size++;//容量++
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()) return null;
        Node<E> temp = head.next;
        //移除节点
        head.next = temp.next;
        //如果删除的是tail节点那我们需要对tail节点的指向重新设置为哨兵
        if (temp == tail) tail = head;
        size--;
        return temp.value;
    }

    @Override
    public E peek() {
        if (isEmpty()) return null;
        return head.next.value;//从哨兵后一个开始获取值 默认头节点为哨兵
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    /**
     * 判断队列元素是否已经达到容量
     *
     * @return 是 否
     */
    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            private Node<E> p = head.next;

            @Override
            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    @Override
    public void forEach(Consumer<? super E> action) {
        Iterable.super.forEach(action);
    }

    @Override
    public Spliterator<E> spliterator() {
        return Iterable.super.spliterator();
    }

    public int size() {
        return this.size;
    }
}
